import { defineStore } from 'pinia';
import { ref } from 'vue';

/**
 * 认证Store
 */
export const useAuthStore = defineStore('auth', () => {
  // 状态
  const user = ref<any>(null);
  const isAuthenticated = ref<boolean>(false);
  const isLoading = ref<boolean>(false);
  const error = ref<string | null>(null);
  const tokenInfo = ref<any>(null);

  // 初始化检查token
  const initialize = async () => {
    isLoading.value = true;
    
    try {
      // 从localStorage获取token
      const token = localStorage.getItem('auth_token');
      
      if (!token) {
        isAuthenticated.value = false;
        user.value = null;
        tokenInfo.value = null;
        isLoading.value = false;
        return;
      }
      
      // 解析token（不发送到服务器验证，直接本地解析）
      const tokenParts = token.split('.');
      if (tokenParts.length !== 3) {
        throw new Error('Invalid token format');
      }
      
      // 解析payload部分
      const payload = JSON.parse(atob(tokenParts[1]));
      
      // 检查token是否过期
      const currentTime = Math.floor(Date.now() / 1000);
      if (payload.exp && payload.exp < currentTime) {
        throw new Error('Token expired');
      }
      
      // 提取用户信息
      user.value = {
        id: payload.sub || payload.userId || payload.id,
        username: payload.username || payload.name || payload.email,
        roles: payload.roles || [],
        permissions: payload.permissions || []
      };
      
      isAuthenticated.value = true;
      tokenInfo.value = payload;
      isLoading.value = false;
      
    } catch (error) {
      console.error('Token validation error:', error);
      // 如果token无效，清除它
      localStorage.removeItem('auth_token');
      isAuthenticated.value = false;
      user.value = null;
      tokenInfo.value = null;
      isLoading.value = false;
      if (error instanceof Error) {
        error.value = error.message;
      }
    }
  };

  // 检查是否有特定角色
  const hasRole = (role: string) => {
    if (!user.value || !user.value.roles) return false;
    return user.value.roles.includes(role);
  };

  // 检查是否有特定权限
  const hasPermission = (permission: string) => {
    if (!user.value || !user.value.permissions) return false;
    return user.value.permissions.includes(permission);
  };

  // 清除状态
  const clearAuth = () => {
    isAuthenticated.value = false;
    user.value = null;
    tokenInfo.value = null;
    error.value = null;
  };

  return {
    user,
    isAuthenticated,
    isLoading,
    error,
    tokenInfo,
    initialize,
    hasRole,
    hasPermission,
    clearAuth,
  };
});
